<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
      <el-form-item :label="t('reviewJudgeScene.fields.studentName')" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          :placeholder="t('common.inputTextPlaceholder') + t('reviewJudgeScene.fields.studentName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-140px"
        />
      </el-form-item>
      <el-form-item :label="t('reviewJudgeScene.fields.jobCode')" prop="jobCode">
        <el-input
          v-model="queryParams.jobCode"
          :placeholder="t('common.inputTextPlaceholder') + t('reviewJudgeScene.fields.jobCode')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-140px"
        />
      </el-form-item>
      <el-form-item :label="t('reviewJudgeScene.fields.studentLevel')" prop="awardLevel">
        <el-select
          v-model="queryParams.awardLevel"
          :placeholder="
            t('common.selectTextPlaceholder') + t('reviewJudgeScene.fields.studentLevel')
          "
          clearable
          @change="handleQuery"
          class="!w-140px"
        >
          <el-option label="硕士研究生" value="硕士研究生" />
          <el-option label="博士研究生" value="博士研究生" />
        </el-select>
      </el-form-item>
      <!--<el-form-item :label="t('reviewJudgeScene.fields.researchDept')" prop="researchDept">-->
      <!--  <el-input-->
      <!--    v-model="queryParams.researchDept"-->
      <!--    :placeholder="-->
      <!--      t('common.inputTextPlaceholder') + t('reviewJudgeScene.fields.researchDept')-->
      <!--    "-->
      <!--    clearable-->
      <!--    @keyup.enter="handleQuery"-->
      <!--    class="!w-140px"-->
      <!--  />-->
      <!--</el-form-item>-->
      <el-form-item :label="t('reviewJudgeScene.fields.major')" prop="major">
        <el-input
          v-model="queryParams.major"
          :placeholder="t('common.inputTextPlaceholder') + t('reviewJudgeScene.fields.major')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-140px"
        />
      </el-form-item>
      <el-form-item :label="t('reviewJudgeScene.fields.accountType')" prop="accountType">
        <el-select
          v-model="queryParams.accountType"
          :placeholder="
            t('common.selectTextPlaceholder') + t('reviewJudgeScene.fields.accountType')
          "
          clearable
          @change="handleQuery"
          class="!w-140px"
        >
          <el-option label="中国科大学生" value="中国科大学生" />
          <el-option label="联合培养学生" value="联合培养学生" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
        <!-- 初评提交结果按钮 -->
        <el-button type="success" :disabled="confirmBtnDisabled" @click="handleOpenSubmitAlert">
          {{ t('reviewJudgeScene.operate.submitResult') }}
        </el-button>

        <el-button type="primary" @click="handleViewSelected" :loading="btnLoading">
          {{ t('reviewJudgeScene.operate.viewSelected') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <!--    <vxe-toolbar ref="toolbarRef" custom />-->
    <vxe-table
      id="iReviewJudge-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        v-if="currentRound?.requireDebate"
        :title="t('reviewJudgeScene.fields.defenseTime')"
        field="debateTime"
        align="center"
        show-header-overflow
        show-overflow
        min-width="120"
      >
        <template #default="scope">
          {{ formatDate(scope.row.debateTime, 'HH:mm') }}
        </template>
      </vxe-column>
      <vxe-column
        :title="t('reviewJudgeScene.fields.jobCode')"
        field="jobCode"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('reviewJudgeScene.fields.studentName')"
        field="studentName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('reviewJudgeScene.fields.gender')"
        field="gender"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('reviewJudgeScene.fields.major')"
        field="major"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('reviewJudgeScene.fields.awardMajor')"
        field="awardMajor"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
        :visible="false"
      />
      <vxe-column
        :title="t('reviewJudgeScene.fields.studentLevel')"
        field="awardLevel"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <!-- <vxe-column -->
      <!--   :title="t('reviewJudgeScene.fields.awardLevel')" -->
      <!--   field="awardLevel" -->
      <!--   align="center" -->
      <!--   show-header-overflow -->
      <!--   show-overflow -->
      <!--   min-width="100" -->
      <!--   :visible="false" -->
      <!-- /> -->
      <vxe-column
        :title="t('reviewJudgeScene.fields.scientificPayoffs')"
        field="scientificPayoffs"
        align="center"
        min-width="180"
      />
      <vxe-column
        :title="t('reviewJudgeScene.fields.applyDetail')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-button link type="primary" @click="handleApplyDetail(scope.row)">
            {{ t('action.detail') }}
          </el-button>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('reviewJudgeScene.fields.historyAwardsJson')"
        field="historyAwardsJson"
        align="center"
        min-width="150"
      />
      <!-- 隐藏申请附件 -->
      <vxe-column
        v-if="false"
        :title="t('reviewJudgeScene.fields.attachment')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <el-button
            v-if="scope.row.attachment && scope.row.attachment !== '[]'"
            link
            type="primary"
            @click="handlePreview(scope.row)"
          >
            {{ t('fileObjectDownload.buttonName') }}
          </el-button>
          <span v-else>{{ t('fileObjectDownload.noFile') }}</span>
        </template>
      </vxe-column>
      <vxe-column
        :title="
          currentRoundReviewMethod === 'VOTE'
            ? t('reviewJudgeScene.operate.vote')
            : t('reviewJudgeScene.operate.recommend')
        "
        field="score"
        align="center"
        show-header-overflow
        show-overflow
        min-width="150"
      />
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="200"
      >
        <template #default="{ row }">
          <!-- 投票 / 取消投票 -->
          <el-tooltip
            v-if="currentRoundReviewMethod === 'VOTE'"
            :content="t('reviewJudgeScene.resultConfirm.confirmedNotOperable')"
            :disabled="!confirmBtnDisabled"
            effect="dark"
            placement="left"
          >
            <!-- 取消投票/投票 -->
            <el-button
              link
              type="primary"
              :loading="voteLoading"
              :disabled="confirmBtnDisabled"
              @click="toggleVote(row)"
            >
              {{
                !row.score
                  ? t('reviewJudgeScene.operate.vote')
                  : t('common.cancel') + t('reviewJudgeScene.operate.vote')
              }}
            </el-button>
          </el-tooltip>
          <!-- 推荐 / 更改推荐 -->
          <VotePopover
            v-if="currentRoundReviewMethod === 'SORT'"
            :disabled="confirmBtnDisabled"
            :row="row"
            :btn-name="
              !row.score
                ? t('reviewJudgeScene.operate.recommend')
                : t('reviewJudgeScene.operate.editRecommend')
            "
            @success="onVoteSuccess"
          />
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 申请详情 -->
  <CandidateApplicationInformation ref="awardStudentApplyInfoRef" />
  <!--  &lt;!&ndash; 推荐/投票弹窗 &ndash;&gt;-->
  <!--  <ReviewJudgeVote-->
  <!--    ref="reviewJudgeVoteRef"-->
  <!--    @success="onVoteSuccess"-->
  <!--  />-->
  <!-- 文件预览弹窗 -->
  <FilePreviewDialog ref="filePreviewRef" type="pdf" />
  <!-- 推荐提交确认提醒弹窗 -->
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :fullscreen="false"
    :show-close="false"
    width="500px"
    top="5vh"
  >
    <!-- 只有SCX初评展示余额 -->
    <div
      v-if="awardsInfo.awardsType === 1 && currentStage?.name === '初评'"
      class="submit-vote-tips"
    >
      <div v-if="totalInitialAwards === 0" class="submit-vote-tips__content">
        <p>您已完成本次评选所有奖项的投票。</p>
        <p>提交后结果将不可修改，请确认是否继续?</p>
      </div>
      <!-- FIXME: 现在没有总数了 -->
      <div v-else class="submit-vote-tips__content">
        <p>当前提交结果中:</p>
        <ul class="pl-20px">
          <li>剩余博士一等/二等/三等可推荐名额: {{ doctorRemaining }}人</li>
          <li>剩余硕士可推荐名额: {{ masterRemaining }}人</li>
        </ul>
        <p>少于可推荐名额，是否确认提交，提交后结果将不可修改。</p>
      </div>
    </div>
    <!-- 其他情况直接走下面的 -->
    <div v-else class="submit-vote-tips">
      <div class="submit-vote-tips__content">
        <p>请确认您已完成所有人投票</p>
        <p>提交后结果将不可修改，请确认是否继续?</p>
      </div>
    </div>
    <template #footer>
      <el-button type="primary" @click="handleSubmitVoteResult">
        {{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { useAppStore } from '@/store/modules/app'
import { useInstanceReviewSceneStore } from '@/store/modules/instance/instanceReivewScene'
// import { vxeDateFormatter } from '@/utils/formatTime'
import { ReviewSceneApi, CandidateJudgesRespVO } from '@/api/awards/reviewscene'
import type { VxeTableInstance, VxeTablePropTypes, VxeToolbarInstance } from 'vxe-table'
import CandidateApplicationInformation from '@/views/awards/components/CandidateApplicationInformation.vue'
import FilePreviewDialog from '@/components/FilePreview/FilePreviewDialog.vue'
import VotePopover from '@/views/awards/instanceReview/VotePopover.vue'
import { formatDate } from '@/utils/formatTime'
// import ReviewJudgeVote from '@/views/awards/instanceReview/ReviewJudgeVote.vue'

/** 初评 */
defineOptions({ name: 'ReviewJudgeTable' })

const instanceReviewSceneStore = useInstanceReviewSceneStore()
// isFinalEnd,
const {
  awardsId,
  awardsInfo,
  currentStage,
  currentRound,
  currentRoundReviewMethod,
  scxInitialRemaining
} = storeToRefs(instanceReviewSceneStore)

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const toolbarRef = ref<VxeToolbarInstance>()
const tableRef = ref<VxeTableInstance>()

const loading = ref(true) // 列表的加载中
const list = ref<CandidateJudgesRespVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 30,
  awardsInstanceId: '', // 评奖ID
  studentLevel: undefined, // 培养层次
  awardLevel: undefined, // 评奖层次
  jobCode: undefined, // 学号
  major: undefined, // 专业
  awardMajor: undefined, // 评奖专业
  studentName: undefined, // 姓名
  accountType: undefined, // 学生类别
  researchDept: undefined, // 研究部
  roundId: '' // 终评轮次ID，初评阶段可不传
})
const queryFormRef = ref() // 搜索的表单

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  queryParams.awardsInstanceId = awardsId.value
  queryParams.roundId = currentRound.value?.roundId ?? ''
  try {
    const data = await ReviewSceneApi.getCandidateJudges(queryParams)
    list.value = data.list.map((item) => {
      let historyAwardsJson = ''
      try {
        historyAwardsJson = JSON.parse(item.historyAwardsJson).join('、')
      } catch {}
      return {
        ...item,
        historyAwardsJson
      }
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 申请详情弹窗
const awardStudentApplyInfoRef = ref<InstanceType<typeof CandidateApplicationInformation>>()
const handleApplyDetail = (row: CandidateJudgesRespVO) => {
  awardStudentApplyInfoRef.value?.open(row.id)
}

// 文件预览弹窗
const filePreviewRef = ref<InstanceType<typeof FilePreviewDialog>>()
const handlePreview = (row: CandidateJudgesRespVO) => {
  filePreviewRef.value?.open(row.attachment)
}

// 推荐/投票弹窗
// const reviewJudgeVoteRef = ref<InstanceType<typeof ReviewJudgeVote>>()
// 投票/推荐
// const handleVote = (row: CandidateJudgesRespVO) => {
//   reviewJudgeVoteRef.value?.open(row)
// }

// 推荐/取消推荐回调
const onVoteSuccess = () => {
  getList()
  // 更新剩余名额
  instanceReviewSceneStore.updateInitialRemaining()
}

// 取消投票/投票
const voteLoading = ref(false)
const toggleVote = async (row: CandidateJudgesRespVO) => {
  voteLoading.value = true
  try {
    await ReviewSceneApi.submitVote({
      awardsInstanceId: row.awardId,
      awardsCandidateId: row.id
    })
    message.success(t('common.operSuccess'))
    getList().then()
    // 更新剩余名额
    instanceReviewSceneStore.updateInitialRemaining()
  } finally {
    voteLoading.value = false
  }
}

// 初评推荐提交结果
const confirmBtnDisabled = ref(false)
const dialogVisible = ref(false) // 提交结果弹窗的是否展示
const dialogTitle = ref('确认提交全部推荐')
const totalInitialAwards = ref(0) // 初评剩余总名额推荐
// const doctorTotal = ref(0) // 博士推荐总名额
// const masterTotal = ref(0) // 硕士推荐总名额
const doctorRemaining = ref(0) // 博士剩余推荐名额
const masterRemaining = ref(0) // 硕士剩余推荐名额

// // sxc剩余名额计算
watch(
  scxInitialRemaining,
  (newVal) => {
    if (!newVal || currentStage.value?.name !== '初评') return
    doctorRemaining.value =
      Number(newVal.doctorFirstRemaining ?? 0) +
      Number(newVal.doctorSecondRemaining ?? 0) +
      Number(newVal.doctorThirdRemaining ?? 0)
    masterRemaining.value = Number(newVal.masterFirstRemaining ?? 0)
    totalInitialAwards.value = doctorRemaining.value + masterRemaining.value
  },
  {
    immediate: true,
    deep: true
  }
)
//
// // scx初评计算硕士和博士的推荐总名额
// // FIXME: 现在没有字段了
// watch(
//   awardsInfo,
//   (newVal) => {
//     if (!newVal || currentStage.value?.name !== '初评') return
//     doctorTotal.value =
//       Number(newVal.awardsDoctorFirstAmount ?? 0) +
//       Number(newVal.awardsDoctorSecondAmount ?? 0) +
//       Number(newVal.awardsDoctorThirdAmount ?? 0)
//     masterTotal.value = Number(newVal.awardsMasterFirstAmount ?? 0)
//   },
//   {
//     immediate: true,
//     deep: true
//   }
// )

// 查询是否可以提交结果
const getCanSubmitResult = async () => {
  if (!awardsId.value || !currentRound.value) return
  try {
    confirmBtnDisabled.value = await ReviewSceneApi.isJudgesConfirmed(
      awardsId.value,
      currentRound.value.roundId
    )
  } catch {}
}

// 打开提交结果弹窗
const handleOpenSubmitAlert = () => {
  dialogVisible.value = true
  dialogTitle.value = totalInitialAwards.value === 0 ? '确认提交全部推荐' : '少于可推荐名额提示'
}

// 确认提交结果
const handleSubmitVoteResult = async () => {
  if (!awardsId.value || !currentRound.value) return
  try {
    await ReviewSceneApi.judgesConfirmRound(awardsId.value, currentRound.value.roundId)
    message.success(t('reviewJudgeScene.resultConfirm.dialog.confirmSuccess'))
    confirmBtnDisabled.value = true
    dialogVisible.value = false
  } catch {}
}

const btnLoading = ref(false)
const handleViewSelected = async () => {
  if (!awardsId.value || !currentRound.value) return
  btnLoading.value = true
  try {
    const data = await ReviewSceneApi.getCandidateJudges({
      pageNo: 1,
      pageSize: -1,
      awardsInstanceId: awardsId.value,
      roundId: currentRound.value.roundId
    })
    const students = data.list
    // 按照score分组 显示名字 null的不要
    const grouped = students.reduce(
      (acc, student) => {
        if (student.score && student.score !== '不推荐') {
          let key = student.score
          if (key === '推荐' && awardsInfo.value.awardsType === 1) {
            key = '硕士推荐'
          }
          if (!acc[key]) {
            acc[key] = []
          }
          acc[key].push(student.studentName + '（' + student.jobCode + '）')
        }
        return acc
      },
      {} as Record<string, string[]>
    )

    let sortKeys = [] as string[]
    // 通用排序
    if (awardsInfo.value.awardsType === 0) {
      sortKeys = Object.keys(grouped).sort((a, b) =>
        a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })
      )
    }

    const order = ['博士一等', '博士二等', '博士三等', '硕士推荐'] // scx排序key
    // scx排序
    if (awardsInfo.value.awardsType === 1) {
      sortKeys = Object.keys(grouped).sort((a, b) => order.indexOf(a) - order.indexOf(b))
    }

    const orderedGrouped = sortKeys.reduce(
      (acc, key) => {
        acc[key] = grouped[key]
        return acc
      },
      {} as Record<string, string[]>
    )

    // 弹窗提示
    const messageContent = Object.entries(orderedGrouped)
      .map(([key, names]) => `<strong>${key}</strong>: ${names.join(', ')}`)
      .join('<br>')
    await ElMessageBox.alert(messageContent, t('reviewJudgeScene.operate.viewSelected'), {
      dangerouslyUseHTMLString: true,
      customStyle: {
        '--el-messagebox-width': '600px'
      }
    })
  } finally {
    btnLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getCanSubmitResult()

  const table = tableRef.value
  const toolbar = toolbarRef.value
  if (table && toolbar) {
    table.connect(toolbar)
  }
})

defineExpose({
  getList,
  resetQuery
})
</script>

<style lang="scss" scoped>
:deep(.vxe-cell .el-button + .el-button) {
  margin-left: 0;
}

.submit-vote-tips {
  &__title {
    font-size: 18px;
    margin-bottom: 10px;
  }
  &__content {
    font-size: 16px;
    line-height: 1.5;
    color: #666;
  }
}
</style>
